package com.jinke.uang.ui.activity.personal;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.R;
import com.jinke.uang.base.BaseNormalActivity;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.bean.PayCodeData;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.RepaymentModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.utils.StringUtils;
import com.jinke.uang.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * todo 获取还款码页面
 */
@Route(name = "获取还款码", path = RouterMap.REPAYMENT_PAGE)
public class RepaymentActivity extends BaseNormalActivity <CommonPresenter, RepaymentModule>{

    private static final int TYPE_OF_ATM = 1;
    private static final int TYPE_OF_OTC = 2;
    public static final String ORDER_ID = "orderId";
    public static final String ORDER_MONEY_NUM = "order_money_num";
    public static final String ORDER_MONEY_IS_ROLLOVER = "order_money_is_rollover";

    @BindView(R.id.tv_pay_num)
    TextView tvPayNum;
    @BindView(R.id.tv_pay_code1)
    TextView tv_pay_code1;
    @BindView(R.id.tv_permata)
    TextView tvPermata;
    @BindView(R.id.tv_preview)
    TextView tvPreview;
    @BindView(R.id.tv_bni)
    TextView tvBni;
    @BindView(R.id.tv_countdown_view)
    TextView tvCountdown;
    @BindView(R.id.btn_acquire)
    TextView btnAcquire;
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;

    @BindView(R.id.pay_code_container1)
    RelativeLayout payCodeContainer1;
    @BindView(R.id.relATMOne)
    RelativeLayout relATM1;
    @BindView(R.id.relATMTwo)
    RelativeLayout relATM2;
    @BindView(R.id.pay_guide)
    TextView payGuide;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindView(R.id.iv2)
    ImageView iv2;

    private CountDownTimer countDownTimer;
    private String mOrderId;
    private String mOrderMoneyNum;
    private boolean isRollover;
    private int mType = TYPE_OF_ATM;
    private boolean isStartCountDown = false;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onUIReady() {
        if (getIntent() == null && StringUtils.isEmpty(getIntent().getStringExtra(ORDER_ID))) {
            ToastUtils.showShort(RepaymentActivity.this, getStringResource(R.string
                    .illegal_params));
            return;
        }
        mOrderId = getIntent().getStringExtra(ORDER_ID);
        mOrderMoneyNum = getIntent().getStringExtra(ORDER_MONEY_NUM);
        isRollover = getIntent().getBooleanExtra(ORDER_MONEY_IS_ROLLOVER, false);

        topText.setText(R.string.repayment_title);

        iv2.setOnClickListener(viewclick);
        iv1.setOnClickListener(viewclick);
        topBack.setOnClickListener(viewclick);
        payGuide.setOnClickListener(viewclick);

        btnAcquire.setOnClickListener(viewclick);

        if (!StringUtils.isEmpty(mOrderMoneyNum)) {
            //还款总金额
            tvPayNum.setText(getStringResource(R.string.money_unit) + StringUtils.getDotMoneyStr
                    (mOrderMoneyNum));

            if(isRollover){
                mPresenter.getData(HttpConstant.ROLLOVER_PAY_CODE_DATA,null,mOrderId);
            }else {
                mPresenter.getData(HttpConstant.PAY_CODE_DATA,null,mOrderId);
            }
            showLoadingView();
        }
    }

    /**
     * 点击信息
     */
    private NoDoubleClickListener viewclick = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            super.onNoDoubleClick(v);
            switch (v.getId()) {
                case R.id.iv1:
                    change();
                    break;
                case R.id.iv2:
                    change();
                    break;
                case R.id.topBack:
                    finish();
                    break;
                case R.id.pay_guide:
                    //指南
                    ARouter.getInstance().build(RouterMap.PAY_GUIDE_PAGE).navigation();
                    break;
                case R.id.btn_acquire:
                    //重新获取
                    ARouter.getInstance().build(RouterMap.PAY_GUIDE_PAGE).navigation();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 改变当前的
     */
    private void change(){
      if(mType == TYPE_OF_ATM){
          //当期是ATM
          iv1.setImageResource(R.drawable.repayment_otc);
          iv2.setImageResource(R.drawable.repayment_atm);
          relATM1.setVisibility(View.GONE);
          relATM2.setVisibility(View.GONE);
          payCodeContainer1.setVisibility(View.VISIBLE);
          tvPreview.setText("ATM");
          mType=TYPE_OF_OTC;

      }else{
          //当期是otc
          iv2.setImageResource(R.drawable.repayment_otc);
          iv1.setImageResource(R.drawable.repayment_atm);
          relATM1.setVisibility(View.VISIBLE);
          relATM2.setVisibility(View.VISIBLE);
          payCodeContainer1.setVisibility(View.GONE);
          tvPreview.setText("OTC");
          mType=TYPE_OF_ATM;
      }

    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_repayment;
    }

    @Override
    public String getPageTitle() {
        return "";
    }

    @Override
    protected int getResId() {
        return 0;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected RepaymentModule getModule() {
        return new RepaymentModule();
    }

    /**
     * 展示数据
     * @param payCodeData
     * @param type
     */
    private void fillView(PayCodeData payCodeData, int type) {
        if (payCodeData == null) {
            if(isRollover){
                mPresenter.getData(HttpConstant.ROLLOVER_PAY_CODE_DATA,null,mOrderId);
            }else {
                mPresenter.getData(HttpConstant.PAY_CODE_DATA,null,mOrderId);
            }
            showLoadingView();
            return;
        }
        mType = type;
        tvPermata.setText(payCodeData.getPayCodeBean().getPermataCode());
        tvBni.setText(payCodeData.getPayCodeBean().getBniCode());

        tv_pay_code1.setText(payCodeData.getPayCodeBean().getOtcCode());

        if (countDownTimer == null) {
            btnAcquire.setEnabled(false);

            isStartCountDown = true;

            countDownTimer = new CountDownTimer(payCodeData.getTimeSeconds() * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    if (tvCountdown != null) {
                        String countDownStr = getFormatTime(millisUntilFinished);

                        tvCountdown.setText(countDownStr);
                    } else {
                        this.cancel();
                        countDownTimer = null;
                        isStartCountDown = false;
                        btnAcquire.setEnabled(true);
                    }
                }

                @Override
                public void onFinish() {
                    isStartCountDown = false;
                    btnAcquire.setEnabled(true);
                    countDownTimer = null;
                }
            }.start();
        }

    }

    StringBuilder timeStr = new StringBuilder();
    private String getFormatTime(long millisUntilFinished) {
        timeStr.delete(0, timeStr.length());

        if (millisUntilFinished < 0) return "";
        Long day = millisUntilFinished / (1000 * 60 * 60 * 24);   //以天数为单位取整
        Long hour = (millisUntilFinished / (60 * 60 * 1000) - day * 24);    //以小时为单位取整
        Long min = ((millisUntilFinished / (60 * 1000)) - day * 24 * 60 - hour * 60); //以分钟为单位取整
        Long second = (millisUntilFinished / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min *
                60);//秒

        if (day > 0) {
            timeStr.append(day).append(":");
        }
        if (hour > 0 || (hour == 0 && timeStr.length() > 0)) {
            formatTime(timeStr, hour).append(":");
        }
        if (min > 0 || (min == 0 && timeStr.length() > 0)) {
            formatTime(timeStr, min).append(":");
        }
        formatTime(timeStr, second);

        return timeStr.toString();
    }

    private StringBuilder formatTime(StringBuilder timeStr, Long time) {
        if (time < 10) {
            timeStr.append("0").append(time);
        } else {
            timeStr.append(time);
        }
        return timeStr;
    }


    //返回值
    @Override
    public void showResponse(int apiType, String listType,Object o) {
            dismissLoadingView();
            BaseResponse<PayCodeData> codeDataBaseResponse = (BaseResponse<PayCodeData>) o;
            if (codeDataBaseResponse.getStatus() == Constant.HTTP_OK) {
                if (codeDataBaseResponse.getData()!=null) {
                    fillView(codeDataBaseResponse.getData(), mType);
                }
            } else {
                ToastUtils.showShort(RepaymentActivity.this, codeDataBaseResponse.getMessage());
            }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
    }
}
